<template>
  <div :class="$style.wrap">
    <Button :type="type" @click="visible=true">{{ title }}</Button>
    <el-dialog :visible.sync="visible" :title="title" :close-on-click-modal="false" @close="resetForm">
      <FormContainer :column="1">
        <el-form ref="form" :model="formData" :rules="formRules" label-width="60px">
          <el-form-item prop="questionTitle" label="标题">
            <el-input v-model="formData.questionTitle" type="textarea" :autosize="{minRows:1}" tip :maxlength="100" placeholder="请输入标题"></el-input>
          </el-form-item>
          <el-form-item>
            <div class="button-container" style="padding-top:0">
              <Button type="primary" @click="visible=false">取消</Button>
              <Button type="primary" @click="confirmHandle">确定</Button>
            </div>
          </el-form-item>
        </el-form>
      </FormContainer>
    </el-dialog>
  </div>
</template>
<script>
import FormContainer from '@/components/FormContainer'
import { questionnaireItemAdd, questionnaireItemUpdate } from '@/api/questionnaire'
import { deepCopy } from '@/utils'
export default {
  name: 'Chapter',
  components: {
    FormContainer
  },
  props: {
    chapterTitle: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: 'primary'
    },
    title: {
      type: String,
      default: '新增标题'
    },
    index: {
      type: Number,
      default: undefined
    },
    questionnaireId: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      visible: false,
      formData: {
        questionTitle: '',
        questionType: 3, // 题目类型：0单选1多选2填空3章节
        scoreType: 0, // 得分类型：0选中扣分1选中得分
        isScore: 0 // 是否评分题：0否 1是
      },
      formRules: {
        questionTitle: [{ required: true, message: '请输入标题', trigger: 'chaneg' }]
      }
    }
  },
  computed: {
    isEdit() {
      return this.id !== '' && this.id !== undefined && this.id !== null
    }
  },
  mounted() {
    this.$set(this.formData, 'questionTitle', this.chapterTitle)
  },
  methods: {
    confirmHandle() {
      return this.$refs.form.validate().then(() => {
        const data = deepCopy(this.formData)
        data.questionnaireId = this.questionnaireId
        data.displaySerialNumber = this.index
        let ajax = questionnaireItemAdd
        if (this.isEdit) {
          ajax = questionnaireItemUpdate
          data.id = this.id
        }
        ajax(data).then(res => {
          this.$message.success('添加成功！')
          this.$emit('on-success', this.questionnaireId)
          this.visible = false
        })
      })
    },
    resetForm() {
      this.$refs.form.resetFields()
    }
  }
}
</script>
<style lang="scss" module>
.wrap{
  display: inline-block;
  text-align: left;
  font-weight: normal;
  margin-right: 10px;
}
</style>
